// pages/goods_list/index.js
import {
  request
} from "../../request/index.js"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs: [{
        id: 0,
        value: "综合",
        isActive: true
      },
      {
        id: 1,
        value: "销量",
        isActive: false
      },
      {
        id: 2,
        value: "价格",
        isActive: false
      }
    ],
    cid: "",
    query: "",
    pagenum:1,
    pagesize:10,
    goodslist: []
  },
  totalPage:1,
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options.cid);
    console.log(options.query);
    this.setData({
      cid: options.cid,
      query: options.query
    })
    this.getGoodsListData();
  },
  changeSelected(e) {
    console.log(e.detail);
    let myTab = this.data.tabs
    myTab.forEach((val, index) => {
      val.isActive = false;
      if (e.detail == index) {
        val.isActive = true;
      }
    });
    this.setData({
      tabs: myTab
    })
  },
  async getGoodsListData() {
    let data = await request({
      url: "https://api-hmugo-web.itheima.net/api/public/v1/goods/search",
      data: {
        cid: this.data.cid || "",
        pagesize: this.data.pagesize,
        query: this.data.query || "",
        pagenum:this.data.pagenum
      }
    })
    console.log(data.data.message);
    this.totalPage=Math.ceil(data.data.message.total/this.data.pagesize);
    this.setData({
      goodslist: [...this.data.goodslist,...data.data.message.goods]
    })
  },
  onReachBottom(){
    console.log(this.totalPage);
    if(this.data.pagenum>=this.totalPage){
      wx.showToast({
        title:"已经没有数据了!"
      })
    }else{
      this.data.pagenum++;
      this.getGoodsListData();
    }
  },
  onPullDownRefresh(){
    this.setData({
      pagenum:1,
      goodslist:[]
    })
    this.getGoodsListData();
    wx.stopPullDownRefresh();
  }
})